# -*- coding: utf-8 -*-
# copyright 2009  Nik Lutz
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#operationDescription
# You should have received a copy of the GNU General Public License
# along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
from PyKDE4.kdeui import *
from PyQt4.QtGui import *
from PyKDE4.plasma import Plasma
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyKDE4.kdecore import *
from PyKDE4.kio import *

class NagiosServiceListItem(QListWidgetItem):
    def __init__(self, service, applet ):
        text =  service.host + "\n" + service.name + "\n"+ service.status_information
        icon = None
        loader = KIconLoader()
        size=22
        bgColor="white"
        if service.status == "CRITICAL":
            icon = KIconLoader.loadIcon(loader, applet.package().path() + "contents/icons/red.svg", KIconLoader.NoGroup,size)
            bgColor="red"
        elif service.status == "WARNING":
            icon = KIconLoader.loadIcon(loader,  applet.package().path() + "contents/icons/yellow.svg", KIconLoader.NoGroup,size)
            bgColor = "yellow"
        else:            
            icon = KIconLoader.loadIcon(loader,  applet.package().path() + "contents/icons/green.svg", KIconLoader.NoGroup,size)        
        QListWidgetItem.__init__( self, QIcon(icon), text)
        
        #self.setBackgroundColor(QColor(bgColor))

class ClickLabel(QLabel):
    def __init__(self):
        QLabel.__init__(self)
        self.connect(self,SIGNAL("mousePressEvent"), self.mousePressEvent)

    def mousePressEvent(self, mouse):
        self.emit(SIGNAL("clicked()"))

class ServiceView(Plasma.Dialog):
    plasmoid = None

    def __init__(self, parent , size):
        Plasma.Dialog.__init__(self)
        self.plasmoid = parent
        
        dialogLayout = QVBoxLayout() 
        self.setLayout(dialogLayout)

        # services tab
        servicesWidget = QWidget()
        servicesLayout = QVBoxLayout()
        servicesWidget.setLayout(servicesLayout)
        servicesList = KListWidget()
        servicesList.setSpacing(0)
        servicesList.setIconSize(QSize(KIconLoader.SizeSmall, KIconLoader.SizeSmall))
        self.connect(servicesList, SIGNAL("itemClicked(QListWidgetItem *)"), self.openNagios)
        servicesLayout.addWidget(servicesList)
        if self.plasmoid.isServiceSearchVisible():
            searchWidget = QWidget()
            searchLayout = QHBoxLayout()
            searchWidget.setLayout(searchLayout)
            
            labelColor = self.palette().text().color().name()
            filterLabel = QLabel()
            filterLabel.setText("<font color=\"%s\">Filter:</font>" % labelColor)            
            searchLine = KListWidgetSearchLine()
            searchLine.setListWidget(servicesList)

            searchLayout.addWidget(filterLabel)
            searchLayout.addWidget(searchLine)
            servicesLayout.addWidget(searchWidget)


        #  Actions tab       
        actionWidget =  QGraphicsView()
        actionLayout = QVBoxLayout()        
        actionWidget.setLayout(actionLayout)

        actionLayout.addStretch()


        actionGoToHosts = QPushButton("Open Hosts")
        actionLayout.addWidget(actionGoToHosts)
        self.connect(actionGoToHosts, SIGNAL("clicked()"), self.openNagiosHosts)

        actionGoToServices = QPushButton("Open Services")
        actionLayout.addWidget(actionGoToServices)
        self.connect(actionGoToServices, SIGNAL("clicked()"), self.openNagiosServices)

        actionGoToNagios = QPushButton("Open Nagios")
        actionLayout.addWidget(actionGoToNagios)
        self.connect(actionGoToNagios, SIGNAL("clicked()"), self.openNagios)

        actionLayout.addWidget(KSeparator())

        actionCheckNow = QPushButton("Check now")
        actionLayout.addWidget(actionCheckNow)
        self.connect(actionCheckNow, SIGNAL("clicked()"), self.checkNow)


        icon = KIcon(self.plasmoid.package().path() + "contents/icons/nagios-plasmoid-128.png")

        toolbox = QToolBox()
        toolbox.setAutoFillBackground (False)
        dialogLayout.addWidget(toolbox)
        style = "QToolBox::tab {} \
                 QToolBox::tab:selected {}"
        #toolbox.setStyleSheet(style)
        toolbox.addItem(servicesWidget, icon ,"Services")
        toolbox.addItem(actionWidget, icon , "Actions")

        #layout.addWidget()
        self.setWindowFlags(Qt.Popup)
        self.setResizeHandleCorners(Plasma.Dialog.All)
        self.resize(size)

        # fill services
        i = 0
        problems = self.plasmoid.getServiceProblems()
        problems.sort(lambda x, y: cmp(str(x.status + x.host), str(y.status+y.host)) )
        for service in problems :
            item = NagiosServiceListItem(service,self.plasmoid)
            if ( i  % 2) == 0:
                item.setBackground( self.palette().mid ())
            servicesList.addItem(item)
            i = i + 1
        #self.show()

        


    def openNagios(self):
        self.openUrl(self.plasmoid.nagios_server.nagios_cgi_url + "/status.cgi?host=all&servicestatustypes=28")

    def openNagiosHosts(self):
        self.openUrl(self.plasmoid.nagios_server.nagios_cgi_url + "/status.cgi?hostgroup=all&style=hostdetail&hoststatustypes=12")

    def openNagiosServices(self):
        self.openUrl(self.plasmoid.nagios_server.nagios_cgi_url+ "/status.cgi?host=all&servicestatustypes=28")

    def openUrl(self, string):
        KRun.runUrl(KUrl(string), QString("text/html"),None)

    def checkNow(self):
        self.plasmoid.checkNow()
        self.hide()


        #self._servicesLayout.setColumnStretch(0, 0)
        #self._servicesLayout.setColumnStretch(1, 1)

        #headerIcon = ClickLabel()
        #self.connect(headerIcon, SIGNAL("clicked()"), self.plasmoid.openNagios)
        #headerIcon.setPixmap(KIcon(self.plasmoid.package().path() + "contents/icons/nagios-plasmoid-128.png").pixmap(KIconLoader.SizeMedium, KIconLoader.SizeMedium))
        #self._servicesLayout.addWidget(headerIcon, 0, 0)

        #labelColor = self.palette().text().color().name()
        #header = QLabel()
        #if len(self.plasmoid._nagios_server.name) > 0:
            #header.setText("<font color=\"%s\">Service Alerts for %s:</font>" % (labelColor, self.plasmoid._nagios_server.name))
        #else:
            #header.setText("<font color=\"%s\">Service Alerts:</font>" % labelColor)
        #self._servicesLayout.addWidget(header, 0, 1)

        #labelColor = self.palette().text().color().name()
        #filterLabel = QLabel()
        #filterLabel.setText("<font color=\"%s\">Filter:</font>" % labelColor)
        #self._servicesLayout.addWidget(filterLabel, 2, 0, 1, 2)

        #searchLine = KListWidgetSearchLine()
        #searchLine.setListWidget(servicesList)
        #self._servicesLayout.addWidget(searchLine, 2, 0, 1, 2)
